// pages/index/index.js
var amapFile = require('../../libs/amap-wx.130.js');

Page({
  data: {
    currentTab: 'suffering',
    modalVisible: false,
    region: 0,
    selectedCityIndex: 0,
    cities: [],
    cityNames: ['请选择'],
    origin: '',
    destination: '',
    originLat: 0,
    originLon: 0,
    destLat: 0,
    destLon: 0,
    transports: [
      { name: '公交地铁', value: 'bus', checked: false },
      { name: '自驾', value: 'car', checked: false },
      { name: '自行车', value: 'bike', checked: false },
      { name: '步行', value: 'walk', checked: false },
      { name: '电动车', value: 'e-bike', checked: false }
    ],
    sufferingRanks: [],
    happyRanks: [],
    currentRank: { suffering: { rank: 0, residence: '', workplace: '', distance: 0 }, happy: { rank: 0, residence: '', workplace: '', distance: 0 } },
    originTips: [],
    originTipsStr: [],
    destinationTips: [],
    destinationTipsStr: [],
    keyboardHeight: 0 // 添加键盘高度
  },

  onLoad() {
    const app = getApp();
    this.amap = new amapFile.AMapWX({ key: 'ad394be13a84430b124d63e3074a15ff' });
    this.fetchRankData(1);
    // 监听键盘高度变化
    wx.onKeyboardHeightChange(res => {
      const keyboardHeight = res.height;
      this.setData({ keyboardHeight });
      this.adjustTipsPosition(); // 键盘变化时调整提示位置
    });
  },

  adjustTipsPosition() {
    const query = wx.createSelectorQuery();
    query.select('#originInput').boundingClientRect();
    query.select('#destinationInput').boundingClientRect();
    query.exec(res => {
      if (res[0]) {
        const originTop = res[0].top + res[0].height + (this.data.keyboardHeight > 0 ? 10 : 5); // 增加偏移量避开键盘
        const originLeft = res[0].left;
        const originWidth = res[0].width;
        this.setData({
          'originTipsStyle': `position: fixed; top: ${originTop}px; left: ${originLeft}px; width: ${originWidth}px; max-height: 200rpx; overflow-y: auto;`
        });
      }
      if (res[1]) {
        const destTop = res[1].top + res[1].height + (this.data.keyboardHeight > 0 ? 10 : 5); // 增加偏移量避开键盘
        const destLeft = res[1].left;
        const destWidth = res[1].width;
        this.setData({
          'destinationTipsStyle': `position: fixed; top: ${destTop}px; left: ${destLeft}px; width: ${destWidth}px; max-height: 200rpx; overflow-y: auto;`
        });
      }
    });
  },

  showOriginTips() {
    this.setData({ originTips: this.data.originTips });
    this.adjustTipsPosition();
  },

  showDestinationTips() {
    this.setData({ destinationTips: this.data.destinationTips });
    this.adjustTipsPosition();
  },

  switchTab(e) {
    this.setData({ currentTab: e.currentTarget.dataset.tab });
  },

  openModal() {
    const validIndex = this.data.cities.length > 0 ? Math.min(this.data.selectedCityIndex, this.data.cityNames.length - 1) : 0;
    this.setData({ region: validIndex, modalVisible: true });
  },

  closeModal() {
    this.setData({ modalVisible: false, originTips: [], originTipsStr: [], destinationTips: [], destinationTipsStr: [] });
  },

  preventDefault() {},

  bindCityChange(e) {
    const value = e.detail.value;
    if (value >= 0 && value < this.data.cityNames.length) {
      this.setData({ selectedCityIndex: value, origin: '', destination: '', originLat: 0, originLon: 0, destLat: 0, destLon: 0 });
      if (value > 0) this.fetchRankData(this.data.cities[value - 1].id);
    } else {
      this.setData({ selectedCityIndex: 0 });
    }
  },

  bindRegionChange(e) {
    const value = e.detail.value;
    if (value >= 0 && value < this.data.cityNames.length) {
      this.setData({ region: value });
    } else {
      this.setData({ region: 0 });
    }
  },

  bindOriginInput(e) {
    this.setData({ origin: e.detail.value });
    this.getTips('origin', e.detail.value);
  },

  bindDestinationInput(e) {
    this.setData({ destination: e.detail.value });
    this.getTips('destination', e.detail.value);
  },

  showOriginTips() {
    this.setData({ originTips: this.data.originTips });
  },

  showDestinationTips() {
    this.setData({ destinationTips: this.data.destinationTips });
  },

  hideTips() {
    setTimeout(() => this.setData({ originTips: [], originTipsStr: [], destinationTips: [], destinationTipsStr: [] }), 200);
  },

  selectOrigin(e) {
    const index = e.currentTarget.dataset.index;
    const itemStr = this.data.originTipsStr[index];
    if (!itemStr) return;
    try {
      const item = JSON.parse(itemStr);
      if (item && item.location) {
        const [lon, lat] = item.location.split(',').map(Number);
        if (isNaN(lon) || isNaN(lat)) return;
        this.setData({ origin: item.name, originLat: lat, originLon: lon, originTips: [], originTipsStr: [] });
      }
    } catch (err) {
      console.error('JSON parse error:', err, 'Item:', itemStr);
    }
  },

  selectDestination(e) {
    const index = e.currentTarget.dataset.index;
    const itemStr = this.data.destinationTipsStr[index];
    if (!itemStr) return;
    try {
      const item = JSON.parse(itemStr);
      if (item && item.location) {
        const [lon, lat] = item.location.split(',').map(Number);
        if (isNaN(lon) || isNaN(lat)) return;
        this.setData({ destination: item.name, destLat: lat, destLon: lon, destinationTips: [], destinationTipsStr: [] });
      }
    } catch (err) {
      console.error('JSON parse error:', err, 'Item:', itemStr);
    }
  },

  getTips(type, keyword) {
    const city = this.data.cities[this.data.region - 1]?.name || '';
    this.amap.getInputtips({
      keywords: keyword,
      city: city,
      success: res => {
        if (res && res.tips) {
          const tips = res.tips;
          const tipsStr = tips.map(item => JSON.stringify(item));
          this.setData({
            [type + 'Tips']: tips,
            [type + 'TipsStr']: tipsStr
          });
        }
      },
      fail: err => {
        console.error('获取提示失败:', err);
      }
    });
  },

  bindTransportChange(e) {
    const values = e.detail.value;
    const transports = this.data.transports.map(item => ({
      ...item,
      checked: values.includes(item.value)
    }));
    this.setData({ transports });
  },

  async submitForm() {
    const { region, origin, destination, originLat, originLon, destLat, destLon, transports, cities } = this.data;
    if (region <= 0 || !origin.trim() || !destination.trim() || originLat === 0 || originLon === 0 || destLat === 0 || destLon === 0) {
      wx.showToast({ title: '请选择城市并填写完整信息', icon: 'none', duration: 2000 });
      return;
    }

    const transportModes = transports.filter(t => t.checked).map(t => t.value).join(',');
    const { env, service } = getApp().getCloudConfig();
    wx.showLoading({ title: '计算中...', mask: true });
    wx.cloud.callContainer({
      config: { env },
      path: '/api/v1/calculateDistance',
      header: { 'X-WX-SERVICE': service, 'Content-Type': 'application/json' },
      method: 'POST',
      data: {
        region: cities[region - 1].id,
        origin,
        destination,
        originLat,
        originLon,
        destLat,
        destLon,
        transports: transportModes
      },
      success: res => {
        wx.hideLoading();
        if (res.data && res.data.code === 0 && res.data.data) {
          const { distance } = res.data.data;
          this.setData({
            currentRank: {
              suffering: { ...this.data.currentRank.suffering, distance },
              happy: { ...this.data.currentRank.happy, distance }
            },
            origin: '',
            destination: '',
            originLat: 0,
            originLon: 0,
            destLat: 0,
            destLon: 0,
            transports: this.data.transports.map(t => ({ ...t, checked: false }))
          });
          this.fetchRankData(cities[region - 1].id);
          this.closeModal();
          wx.showToast({ title: `提交成功，距离 ${distance} 公里`, icon: 'success', duration: 2000 });
        } else {
          wx.showToast({ title: res.data?.message || '计算失败', icon: 'none', duration: 2000 });
        }
      },
      fail: err => {
        wx.hideLoading();
        wx.showToast({ title: '网络错误', icon: 'none', duration: 2000 });
        console.error(err);
      }
    });
  },

  fetchRankData(regionId) {
    const { env, service } = getApp().getCloudConfig();
    wx.cloud.callContainer({
      config: { env },
      path: `/api/v1/rank/list?region=${regionId}`,
      header: { 'X-WX-SERVICE': service, 'Content-Type': 'application/json' },
      method: 'GET',
      success: res => {
        if (res.data && res.data.code === 0 && res.data.data) {
          const cities = res.data.data.cities || [];
          this.setData({
            sufferingRanks: res.data.data.sufferingRanks || [],
            happyRanks: res.data.data.happyRanks || [],
            currentRank: res.data.data.currentRank || { suffering: { rank: 0, residence: '', workplace: '', distance: 0 }, happy: { rank: 0, residence: '', workplace: '', distance: 0 } },
            cities,
            cityNames: ['请选择', ...cities.map(city => city.name)]
          });
        } else {
          wx.showToast({ title: '加载排名失败', icon: 'none', duration: 2000 });
        }
      },
      fail: err => {
        wx.showToast({ title: '网络错误', icon: 'none', duration: 2000 });
        console.error(err);
      }
    });
  },

  share() {
    wx.showToast({ title: '分享功能待实现', icon: 'none' });
  }
});